package com.example.demo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "EnvParamServlet", value = "/EnvParamServlet")
public class EnvParamServlet extends HttpServlet {
    private static final String DB_URL = "jdbc:mysql://172.18.64.254:3306/三人行?useSSL=false&serverTimezone=UTC&characterEncoding=utf8";
    private static final String DB_USER = "webdb";
    private static final String DB_PASSWORD = "webdb";

    // 查询环境参数列表
    private List<Map<String, Object>> queryEnvParams(String area) throws SQLException {
        List<Map<String, Object>> list = new ArrayList<>();
        String sql = "SELECT * FROM env_param " +
                (area != null && !area.isEmpty() ? "WHERE env_area LIKE ? " : "") +
                "ORDER BY create_time DESC";

        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            if (area != null && !area.isEmpty()) {
                pstmt.setString(1, "%" + area + "%");
            }

            ResultSet rs = pstmt.executeQuery();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

            while (rs.next()) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", rs.getInt("id"));
                map.put("envArea", rs.getString("env_area"));
                map.put("temperature", rs.getDouble("temperature"));
                map.put("humidity", rs.getDouble("humidity"));
                map.put("smokeConcentration", rs.getDouble("smoke_concentration"));

                Timestamp createTime = rs.getTimestamp("create_time");
                map.put("createTime", createTime != null ? sdf.format(createTime) : "无记录");
                list.add(map);
            }
        }
        return list;
    }

    // 获取单个环境参数
    private Map<String, Object> getEnvParam(int id) throws SQLException {
        Map<String, Object> map = new HashMap<>();
        String sql = "SELECT * FROM env_param WHERE id = ?";

        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, id);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                map.put("id", rs.getInt("id"));
                map.put("envArea", rs.getString("env_area"));
                map.put("temperature", rs.getDouble("temperature"));
                map.put("humidity", rs.getDouble("humidity"));
                map.put("smokeConcentration", rs.getDouble("smoke_concentration"));

                Timestamp createTime = rs.getTimestamp("create_time");
                map.put("createTime", createTime != null ? sdf.format(createTime) : "无记录");
            }
        }
        return map;
    }

    // 保存环境参数（新增/更新）
    private void saveEnvParam(Map<String, String> paramMap, boolean isUpdate) throws SQLException {
        String sql = isUpdate ?
                "UPDATE env_param SET env_area=?, temperature=?, humidity=?, smoke_concentration=? WHERE id=?" :
                "INSERT INTO env_param (env_area, temperature, humidity, smoke_concentration) VALUES (?, ?, ?, ?)";

        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, paramMap.get("envArea"));
            pstmt.setDouble(2, Double.parseDouble(paramMap.get("temperature")));
            pstmt.setDouble(3, Double.parseDouble(paramMap.get("humidity")));
            pstmt.setDouble(4, Double.parseDouble(paramMap.get("smokeConcentration")));

            if (isUpdate) {
                pstmt.setInt(5, Integer.parseInt(paramMap.get("id")));
            }

            pstmt.executeUpdate();
        }
    }

    // 删除环境参数
    private void deleteEnvParam(int id) throws SQLException {
        String sql = "DELETE FROM env_param WHERE id = ?";
        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, id);
            pstmt.executeUpdate();
        }
    }

    // 处理 GET 请求
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();

        String action = request.getParameter("action");
        try {
            if ("list".equals(action)) {
                String area = request.getParameter("area");
                List<Map<String, Object>> list = queryEnvParams(area);
                out.println(toJsonArray(list));

            } else if ("get".equals(action)) {
                String idStr = request.getParameter("id");
                if (idStr == null || idStr.isEmpty()) {
                    throw new IllegalArgumentException("缺少参数: id");
                }

                int id = Integer.parseInt(idStr);
                Map<String, Object> param = getEnvParam(id);
                if (param.isEmpty()) {
                    out.println("{\"error\": \"未找到对应记录\"}");
                } else {
                    out.println(toJson(param));
                }

            } else if ("delete".equals(action)) {
                String idStr = request.getParameter("id");
                if (idStr == null || idStr.isEmpty()) {
                    throw new IllegalArgumentException("缺少参数: id");
                }

                int id = Integer.parseInt(idStr);
                deleteEnvParam(id);
                out.println("{\"success\": true}");

            } else {
                out.println("{\"error\": \"无效的操作(action)\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.println("{\"error\": \"" + e.getMessage() + "\"}");
        }
    }

    // 处理 POST 请求
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();

        String action = request.getParameter("action");
        try {
            if ("add".equals(action) || "update".equals(action)) {
                // 获取表单参数
                String envArea = request.getParameter("envArea");
                String temperature = request.getParameter("temperature");
                String humidity = request.getParameter("humidity");
                String smokeConcentration = request.getParameter("smokeConcentration");

                // 参数验证
                if (envArea == null || envArea.isEmpty() ||
                        temperature == null || temperature.isEmpty() ||
                        humidity == null || humidity.isEmpty() ||
                        smokeConcentration == null || smokeConcentration.isEmpty()) {
                    throw new IllegalArgumentException("参数不完整");
                }

                Map<String, String> paramMap = new HashMap<>();
                paramMap.put("envArea", envArea);
                paramMap.put("temperature", temperature);
                paramMap.put("humidity", humidity);
                paramMap.put("smokeConcentration", smokeConcentration);

                if ("update".equals(action)) {
                    String idStr = request.getParameter("id");
                    if (idStr == null || idStr.isEmpty()) {
                        throw new IllegalArgumentException("缺少参数: id");
                    }
                    paramMap.put("id", idStr);
                }

                saveEnvParam(paramMap, "update".equals(action));
                out.println("{\"success\": true}");

            } else {
                out.println("{\"error\": \"无效的操作(action)\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.println("{\"error\": \"" + e.getMessage() + "\"}");
        }
    }

    // 将 Map 转换为 JSON 字符串
    private String toJson(Map<String, Object> map) {
        StringBuilder json = new StringBuilder("{");
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            json.append("\"").append(entry.getKey()).append("\":");
            if (entry.getValue() instanceof String) {
                json.append("\"").append(entry.getValue()).append("\"");
            } else {
                json.append(entry.getValue());
            }
            json.append(",");
        }
        if (json.length() > 1) json.setLength(json.length() - 1);
        json.append("}");
        return json.toString();
    }

    // 将 List<Map> 转换为 JSON 数组
    private String toJsonArray(List<Map<String, Object>> list) {
        StringBuilder json = new StringBuilder("[");
        for (int i = 0; i < list.size(); i++) {
            if (i > 0) json.append(",");
            json.append(toJson(list.get(i)));
        }
        json.append("]");
        return json.toString();
    }

    // 获取数据库连接
    private Connection getConnection() throws SQLException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new SQLException("JDBC驱动加载失败", e);
        }
        return DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
    }
}